package qqclient.service;

import qqcommon.Message;
import qqcommon.MessageType;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ClientConnectServerThread extends Thread {
    private Socket socket;
    public ClientConnectServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //因为Thread需要在后台运行，所以要while循环
        while(true) {
            try {
                System.out.println("客户端线程，等待读取从服务端发送的消息");
                ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
                Message message=(Message)ois.readObject();
                if(message.getMesType().equals(MessageType.MESSAGE_RET_ONLINE_FRIEND))
                {
                    String[] onlineUsers=message.getContent().split(" ");
                    System.out.println("===========当前在线用户列表===========");
                    for(String onlineUser:onlineUsers)
                    {
                        System.out.println("用户："+onlineUser);
                    }
                }
                else if(message.getMesType().equals(MessageType.MESSAGE_COMM_MES))
                {
                    System.out.println("\n"+message.getSender()+" 对 "+message.getGetter()+" 说 "+message.getContent());
                }
                else if(message.getMesType().equals(MessageType.MESSAGE_TO_ALL))
                {
                    System.out.println("\n"+message.getSender()+" 对大家说 "+message.getContent());
                }
                else if(message.getMesType().equals(MessageType.MESSAGE_FILE_MES))
                {
                    System.out.println("\n"+message.getSender()+" 给 "+message.getGetter()+" 发送了文件");
                    System.out.println("保存路径："+message.getDest());
                    FileOutputStream fileOutputStream=new FileOutputStream(message.getDest());
                    fileOutputStream.write(message.getFileBytes());
                    fileOutputStream.close();
                    System.out.println("\n保存文件成功！");
                }
                else
                {
                    System.out.println("其他类型的message");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
    public Socket getSocket() {
        return socket;
    }
}
